#include "interrupt.h"
#include "timer.h"

struct timer_regs
{
    unsigned Load;
    unsigned Value;
    unsigned Control;
    unsigned IntClr;
    unsigned RIS;
    unsigned MIS;
    unsigned BGLoad;
};

#define TIMER1 (*(volatile struct timer_regs *)0x13000100)

static void (* on_timer_tick)(void);

static void handle_timer1(void)
{
    if (TIMER1.MIS & 1)
    {
        if (on_timer_tick) on_timer_tick();
        TIMER1.IntClr = 0;
    }
}

void init_timer(void)
{
    disable_irq_interrupt(TIMERINT1);

    TIMER1.IntClr = 0;

    enable_irq_interrupt(TIMERINT1);

    set_irq_handler(TIMERINT1, handle_timer1);

    // ENABLE = 1 (timer enable)
    // MODE = 0 (free running)
    // IE = 1 (interrupt enable)
    // PRESCALE = 01 (divide by 16)
    // TimerSize = 0 (16-bit counter)
    // OneShotCount = 0 (wrapping mode)
    TIMER1.Control = 0b10100100;
}

void set_on_timer_tick(void (*handler)(void))
{
    on_timer_tick = handler;
}
